package com.fragment;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


import com.activities.Front_items_activity;
import com.activities.MapInformation;
import com.activities.TopciInformation;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bean.News;
import com.bean.TopPager;

import com.dbs.DataHelper;
import com.example.lizhiinformation.R;
import com.me.maxwin.view.XListView;
import com.me.maxwin.view.XListView.IXListViewListener;
import com.myadapter.FrontPage_Topadapter;
import com.myadapter.FrontPageadapter;
import com.ownload.Httputil;
import com.ownload.Httputil.OnNetWorkRespones;
import com.tools.Path_URL;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
@SuppressLint("NewApi")
public class FrontPage extends Fragment implements IXListViewListener {
	private FrontPageadapter adapter;
	private int canter = 1;

	ListView mlistView;
	private View loadview;
	private View view2;
	private ViewPager viewpage;
	private RadioGroup radiogroup;
	private Timer timer;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		loadview = inflater.inflate(R.layout.listview_no, null);
		
		return inflater.inflate(R.layout.fromtpage_main, container, false);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		
		mlistView = (ListView) view.findViewById(R.id.fromtpagelistview);
		findview();
//		mlistView.setVisibility(View.GONE);
		
		if(new DataHelper(getActivity()).query("1", "头条")!=null){
			setvalues(new DataHelper(getActivity()).query("1", "头条"));	
		}else{
			Setlistview(mlistView);
		}
		if(new DataHelper(getActivity()).query("1", "头条头部")!=null){
			settopvalues(new DataHelper(getActivity()).query("1", "头条头部"));			
		}else{
			frame();
		}
		listviewadd();
	}
	// 头部刷新
	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		Setlistview(mlistView);
		if(new DataHelper(getActivity()).query("1", "头条")!=null){
			setvalues(new DataHelper(getActivity()).query("1", "头条"));
		}
		onLoad();
	}

	// 上拉加载
	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		canter++;		
		if(new DataHelper(getActivity()).query(String.valueOf(canter), "头条")!=null){
			addvalues(new DataHelper(getActivity()).query(String.valueOf(canter), "头条"));
		}else{
			addlistview(mlistView, canter);
			onLoad();
		}
	}

	//listview数据下载
	public void Setlistview(final ListView mlistView) {

		Httputil.OnWorkDown(Path_URL.FRONTPAGEURL1 + 1
				+ Path_URL.FRONTPAGEURL2, new OnNetWorkRespones() {
			
			@Override
			public void OK(String respose) {
				new DataHelper(getActivity()).insert(respose, "头条", "1");
				setvalues(new DataHelper(getActivity()).query("1", "头条"));
				
				frame();
				
			}

			@Override
			public void ERROR(String error) {

			}
		});

	}

	/**
	 * listview添加
	 * 
	 * @param mListView
	 * @param code
	 */
	public void addlistview(ListView mListView, final int code) {

		Httputil.OnWorkDown(Path_URL.FRONTPAGEURL1 + String.valueOf(code)
				+ Path_URL.FRONTPAGEURL2, new OnNetWorkRespones() {
			@Override
			public void OK(String respose) {
				new DataHelper(getActivity()).insert(respose, "头条", String.valueOf(code));	
				addvalues(new DataHelper(getActivity()).query(String.valueOf(canter), "头条"));
				frame();
				
			}
			@Override
			public void ERROR(String error) {

			}
		});
	}

	// 停止加载和刷新动画
	private void onLoad() {
		((XListView) mlistView).stopRefresh();
		((XListView) mlistView).stopLoadMore();
		SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日      HH:mm ");
		long millis = System.currentTimeMillis();
		Date date = new Date(millis);
		String format = sdf.format(date);
		((XListView) mlistView).setRefreshTime(format);

	}

	/**
	 * listview头部数据下载
	 */
	public void frame() {
		
		Httputil.OnWorkDown(Path_URL.TOP_URL, new OnNetWorkRespones() {

			@Override
			public void OK(String respose) {
				// TODO Auto-generated method stub
				new DataHelper(getActivity()).insert(respose, "头条头部", "1");	
				settopvalues(new DataHelper(getActivity()).query("1", "头条头部"));
				
				
			}
			@Override
			public void ERROR(String error) {
				// TODO Auto-generated method stub
			}
		});
		
	}

	/**
	 * 初始化组件
	 */
	public void findview() {

		((XListView) mlistView).setPullLoadEnable(true);
		((XListView) mlistView).setXListViewListener(this);
		view2 = getActivity().getLayoutInflater().inflate(R.layout.top_page,
				null);
		viewpage = (ViewPager) view2.findViewById(R.id.vp_news_top);
		radiogroup = (RadioGroup) view2.findViewById(R.id.radioGroup1);
	}
	//listview开始第一页数据加载
	public void setvalues(String values){
		JSONObject object = JSONObject.parseObject(values);
		String status = object.getString("status");
		
		if (status.equals("ok")) {
			JSONObject paramz = object.getJSONObject("paramz");
			JSONArray feeds = paramz.getJSONArray("feeds");

			List<News> newsList = JSONArray.parseArray(
					feeds.toJSONString(), News.class);

			adapter = new FrontPageadapter(getActivity(), newsList,
					mlistView);

			mlistView.setAdapter(adapter);
			mlistView.setVisibility(View.VISIBLE);
		}
		
	}
	
	
	
	
	//加载更多listview的数据
	
	public void addvalues(String values){
		JSONObject object = JSONObject.parseObject(values);
		String status = object.getString("status");
		if (status.equals("ok")) {
			JSONObject paramz = object.getJSONObject("paramz");
			JSONArray feeds = paramz.getJSONArray("feeds");

			List<News> newsList1 = JSONArray.parseArray(
					feeds.toJSONString(), News.class);
			adapter.addData(newsList1);
		}
		}
	/**
	 * 头部数据设置
	 * @param respose
	 */
	public void settopvalues(String respose){
		JSONObject object = (JSONObject) JSONObject.parse(respose);
		String status = object.getString("status");
		
		if (status.equals("ok")) {
			JSONObject paramz = object.getJSONObject("paramz");
			JSONArray tops = paramz.getJSONArray("tops");
			List<TopPager> topPagers = JSONArray.parseArray(
					tops.toJSONString(), TopPager.class);
			FrontPage_Topadapter topadapter = new FrontPage_Topadapter(
					topPagers, getActivity());
			viewpage.setOnPageChangeListener(new OnPageChangeListener() {

				@Override
				public void onPageSelected(int arg0) {
					// TODO Auto-generated method stub
					RadioButton childAt = (RadioButton) radiogroup
							.getChildAt(arg0);
					childAt.setChecked(true);
				}

				@Override
				public void onPageScrolled(int arg0, float arg1,
						int arg2) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onPageScrollStateChanged(int arg0) {
					// TODO Auto-generated method stub

				}
			});
			viewpage.setAdapter(topadapter);
			// 设置viewpager的自动跳转
			 final Handler handler = new Handler(){
				public void handleMessage(android.os.Message msg) {
					int item = viewpage.getCurrentItem();
					int code = item + 1;
					if (code == 5) {
						code = 0;
					}
					viewpage.setCurrentItem(code);
				};
			 };
			
			timer = new Timer();
			timer.schedule(new TimerTask() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					
					handler.sendEmptyMessage(0);
				}
			}, 0, 4000);

		}
	}
	/**
	 * listview添加头部和点击事件
	 */
	public void listviewadd(){
		mlistView.addHeaderView(view2);
		mlistView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				// TODO Auto-generated method stub
				String[] split = adapter.getItem(position).split(":");
				switch (split[0].length()) {
				case 6:
					if(split[1].equals("video")){
						
					}
						Intent intent = new Intent(getActivity(),
								Front_items_activity.class);
						intent.putExtra("url", split[0]);
						startActivity(intent);
					
					
										
					break;
				case 3:
					Intent intent1 = new Intent(getActivity(),
							TopciInformation.class);
					intent1.putExtra("id", split[0]);
					startActivity(intent1);
					break;
				case 4:
					Intent intent2 = new Intent(getActivity(),
							MapInformation.class);
					intent2.putExtra("url", split[0]);
					startActivity(intent2);
					break;
				default:
					Toast.makeText(getActivity(), "该信息没有添加", 0).show();
					break;
				}			
			}
		});

	  }
	//销毁时把计时器关掉
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		timer.cancel();
		
	}
}
